﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
    private Vector2 draggingOffset = new Vector2(0.0f, 40.0f); // 拖拽过程中物体的偏置
    private GameObject draggingObject; // 保存拖拽过程中的对象
    private RectTransform canvasRectTransform; // 保存画布的Rect Transform

    public void OnBeginDrag(PointerEventData pointerEventData)
    {
        if (draggingObject != null)
        {
            Destroy(draggingObject);
        }
        // 获取物体的Image组件
        Image sourceImage = GetComponent<Image>();
        // 创建拖拽过程中物体的对象
        draggingObject = new GameObject("Dargging Object");
        // 设置为原物体的画布子元素，显示在最前面
        draggingObject.transform.SetParent(sourceImage.canvas.transform);
        draggingObject.transform.SetAsLastSibling();
        draggingObject.transform.localScale = Vector3.one;
        // 使用Canvas Group组件的Block Raycast属性
        // 让光线投射不被阻隔
        CanvasGroup canvasGroup = draggingObject.AddComponent<CanvasGroup>();
        canvasGroup.blocksRaycasts = false;
        // 为拖拽过程中物体的对象附加Image组件
        Image draggingImage = draggingObject.AddComponent<Image>();
        // 设置为与原物体相同的外观
        draggingImage.sprite = sourceImage.sprite;
        draggingImage.rectTransform.sizeDelta = sourceImage.rectTransform.sizeDelta;
        draggingImage.color = sourceImage.color;
        draggingImage.material = sourceImage.material;
        // 保存画布的Rect Transform
        canvasRectTransform = draggingImage.canvas.transform as RectTransform;
        // 更新拖拽过程中的物体位置
        UpdateDraggingObjectPos(pointerEventData);
    }

    public void OnDrag(PointerEventData pointerEventData)
    {
        UpdateDraggingObjectPos(pointerEventData);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Destroy(draggingObject);
    }


    private void UpdateDraggingObjectPos(PointerEventData pointerEventData)
    {
        Image sourceImage = GetComponent<Image>();
        if (draggingObject != null)
        {
            // 计算拖拽过程中物体的屏幕坐标
            Vector3 screenPos = pointerEventData.position + draggingOffset;
            // 将屏幕坐标转换为世界坐标
            Camera camera = pointerEventData.pressEventCamera;
            Vector3 newPos;
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(canvasRectTransform, screenPos, camera, out newPos))
            {
                // 将拖拽过程中的物体位置以世界坐标设置
                draggingObject.transform.position = newPos;
                draggingObject.transform.rotation = canvasRectTransform.rotation;
                // 直接改变原物体的位置
                sourceImage.transform.position = newPos;
            }
        }
    }

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

}
